package com.suitsoft.bdms.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.http.Header;
import org.apache.http.cookie.Cookie;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.utils.web.struts2.Struts2Utils;

import com.opensymphony.xwork2.ActionSupport;
import com.suitsoft.bdms.commos.HttpPostLogin;
import com.suitsoft.bdms.commos.LoginUser;
import com.suitsoft.bdms.commos.UserHolder;
import com.suitsoft.bdms.entity.system.PointEntity;
import com.suitsoft.bdms.entity.system.SubPointEntiry;
import com.suitsoft.bdms.service.system.PointInfoManager;
import com.suitsoft.bdms.service.system.SubPointManager;

/**
 * 单点登陆
 *@author Suineg
 */
@SuppressWarnings("serial")
@Results( { @Result(name = "RELOGIN", location = "login.action", type = "redirect") })
public class PointLoginAction extends ActionSupport{
	/** 日志输出对象 */
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	/** 重新登陆  */
	private final String RELOGIN = "RELOGIN";
	/** 登陆-并跳转 */
	private final String LOGIN1 = "login1";
	/** 登陆 */
	private final String LOGIN = "login";
	
	@SuppressWarnings("unused")
	private final String SUBMIT_SIGINS = "j_spring_security_check";
	
	private PointInfoManager manager;
	private SubPointManager subPointManager;
	
	
	/** 当前登陆用户 */
	private LoginUser loginUser;
	/** 提交的链接   在这里可以改成 从指定的地方 取出。。这样就可以实现..URL的控制*/
	private String url = "http://192.168.1.117:8080/hrq/j_spring_security_check";
	
	/** 子系统列表 */
	private List<PointEntity> list;
	/** ID */
	private Long id;
	/** 实体 */
	private PointEntity entity;
	/** 应用ID */
	private Long sid;
	/** 子系统的具体应用实体 */
	private SubPointEntiry subPointEntiry;
	private List<SubPointEntiry> subpointList;
	
	/**
	 * 子系统列表
	 * @return
	 */
	public String execute() throws Exception {
		loginUser = UserHolder.getLoginUser();
		if(loginUser == null){
			return RELOGIN;
		}
		list = manager.getAll();
		Map<String,Object> syucUser = subPointManager.findSycUserByLoginName(loginUser.getLoginName());
		String userType = syucUser.get("USER_TYPE") == null ? "" : syucUser.get("USER_TYPE").toString();
		if("学生".equals(userType)){
			Struts2Utils.getRequest().setAttribute("f", "1");
		}else{
			Struts2Utils.getRequest().setAttribute("f", "2");
		}
		return SUCCESS;
	}
	
	public String login(){
		if(id == null || id == 0L){
			addActionMessage("非法操作");
			return SUCCESS;
		}
		entity = manager.get(id);
		if(entity == null){
			addActionMessage("非法操作");
			return SUCCESS;
		}
		loginUser = UserHolder.getLoginUser();
		if(loginUser == null){
			return RELOGIN;
		}
		
		return LOGIN;
	}
	
	/**
	 * 新版
	 * @return
	 */
	public String loginNew(){
		if(id == null || id == 0L || sid == null || sid == 0L){
			addActionMessage("非法操作");
			return SUCCESS;
		}
		entity = manager.get(id);
		if(entity == null){
			addActionMessage("非法操作");
			return SUCCESS;
		}
		subPointEntiry = subPointManager.get(sid);
		if(subPointEntiry == null){
			addActionMessage("非法操作");
			return SUCCESS;
		}
		loginUser = UserHolder.getLoginUser();
		if(loginUser == null){
			return RELOGIN;
		}
		Map<String,String> userPass = new HashMap<String,String>();
		userPass.put(entity.getUsername(), loginUser.getLoginName());
		userPass.put(entity.getPassword(), loginUser.getPassword());
		HttpPostLogin httpPost = null;
		httpPost = new HttpPostLogin(entity.getUrl(),userPass);
		
		try {
			HttpServletResponse response = Struts2Utils.getResponse();
//			if(httpPost.isLoginSuccess()){
			httpPost.isLoginSuccess();
				
				//设置header，并把SessionID找到
				String sessionid = "";
				for(Header h : httpPost.getAllHeader()){
					response.addHeader(h.getName(), h.getValue());
					if(h.getName().equals("Set-Cookie")){
						sessionid = h.getValue();
						sessionid = sessionid.substring(sessionid.indexOf("=") + 1, sessionid.indexOf(";"));
					}
				}
				
				//设置cookie
				for(Cookie c : httpPost.getAllCookie()){
					javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie(c.getName(), c.getValue());
					cookie.setComment(c.getComment());
					cookie.setDomain(c.getDomain());
					cookie.setPath(c.getPath());
					cookie.setVersion(c.getVersion());
					response.addCookie(cookie);
				}
				String url = subPointEntiry.getUrl();
				System.out.println(sessionid);
				if(url.indexOf("?") != -1){
					String ss[] = url.split("\\?");
					url = ss[0]  + ";jsessionid=" +sessionid + "?" + ss[1];
				}else{
					url += ";jsessionid=" +sessionid;
				}
				response.sendRedirect(url);
//			}else{
//				addActionMessage("登陆失败");
//				return SUCCESS;
//			}
			httpPost.isLoginSuccess();
		} catch (IOException e) {
			e.printStackTrace();
			addActionMessage("操作失败！");
			return SUCCESS;
		}
		return null;
	}
	
	public String login1(){
		if(id == null || id == 0L || sid == null || sid == 0L){
			addActionMessage("非法操作");
			return SUCCESS;
		}
		entity = manager.get(id);
		if(entity == null){
			addActionMessage("非法操作");
			return SUCCESS;
		}
		subPointEntiry = subPointManager.get(sid);
		if(subPointEntiry == null){
			addActionMessage("非法操作");
			return SUCCESS;
		}
		loginUser = UserHolder.getLoginUser();
		if(loginUser == null){
			return RELOGIN;
		}
		
		return LOGIN1;
	}
	
	/**
	 * 获取用名和密码
	 * @return
	 */
	public String namePasswd(){
		try {
			PrintWriter out = Struts2Utils.getResponse().getWriter();
			loginUser = UserHolder.getLoginUser();
			JSONObject obj = new JSONObject();
			if(loginUser != null){
				obj.put("name", loginUser.getLoginName());
				obj.put("passwd", loginUser.getPassword());
			}else{
				return null;
			}
			out.print(obj.toString());
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	public LoginUser getLoginUser() {
		return loginUser;
	}
	public void setLoginUser(LoginUser loginUser) {
		this.loginUser = loginUser;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public List<PointEntity> getList() {
		return list;
	}
	public void setList(List<PointEntity> list) {
		this.list = list;
	}
	@Autowired
	public void setManager(PointInfoManager manager) {
		this.manager = manager;
	}
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}

	public PointEntity getEntity() {
		return entity;
	}

	public void setEntity(PointEntity entity) {
		this.entity = entity;
	}

	public Long getSid() {
		return sid;
	}

	public void setSid(Long sid) {
		this.sid = sid;
	}

	public SubPointEntiry getSubPointEntiry() {
		return subPointEntiry;
	}

	public void setSubPointEntiry(SubPointEntiry subPointEntiry) {
		this.subPointEntiry = subPointEntiry;
	}
	@Autowired
	public void setSubPointManager(SubPointManager subPointManager) {
		this.subPointManager = subPointManager;
	}

	public List<SubPointEntiry> getSubpointList() {
		return subpointList;
	}

	public void setSubpointList(List<SubPointEntiry> subpointList) {
		this.subpointList = subpointList;
	}
}

